import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2btrailer/b2btrailerlogisticsscreen.dart';
import 'package:opene/ui/b2btrailer/b2btrailerselfpickupscreen.dart';
import 'package:opene/ui/b2btrailer/b2btrailermodel.dart';
import 'package:opene/ui/b2coblpn/b2coblpnsubmitscreen.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailermodel.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailersubmitscreen.dart';
import 'package:toast/toast.dart';

class B2BTrailerScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return B2BTrailerScreenPage();
  }
}

class B2BTrailerScreenPage extends StatefulWidget {
  @override
  _B2BTrailerPageState createState() => _B2BTrailerPageState();
}

class _B2BTrailerPageState extends BaseState<B2BTrailerScreen> {
  bool layoutPalletTag = false, tvPalletHint = false, tvPrint = false, layoutOrder = true, layoutTrailer = false;
  String order, tvPallet;
  TrailerBean trailerBean;
  List<B2BTrailer> b2BTrailers;
  B2BTrailer b2BTrailer;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Trailer#";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _updateRadio(2);
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTrailerInitData();
      });
    });
  }

  void _updateRadio(int value) {
    setState(() {
      code = "";
      hint = "";
      this.type = value;
      order = "";
      tvPallet = "";
      layoutPalletTag = false;
      tvPalletHint = false;
      tvPrint = false;
      if (type == 2) {
        layoutOrder = true;
        layoutTrailer = false;
      } else {
        layoutOrder = false;
        layoutTrailer = true;
      }
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Logistics",
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(1);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Selfpickup",
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(2);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
            visible: layoutTrailer,
            child: Container(
              margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
              width: double.infinity,
              child: ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 35),
                child: TextField(
                  controller: textEditingController,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (String text) {
                    print('Searching for $text');
                    if (Utils.isEmpty(text)) {
                      return;
                    }
                  },
                  // autofocus: true,
                  decoration: InputDecoration(
                    suffixIcon: IconButton(
                      padding: EdgeInsets.all(2.0),
                      icon: Icon(
                        Icons.qr_code_scanner,
                        size: 28,
                        color: MyAppTheme.nearlyBlue,
                      ),
                      onPressed: () {
                        // requestPermissions();
                        // Utils.scanBarcode(context);
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                          return ScanCode();
                        })).then((text) {
                          if (text == null) {
                            return;
                          }
                          setState(() {
                            textEditingController.text = text;
                          });
                          print(text); //拿到扫描结果
                        });
                      },
                    ),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: MyAppTheme.nearlyBlue,
                      ),
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点之外的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点时的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    hintText: "scan trailer#",
                    filled: true,
                    fillColor: MyAppTheme.white,
                    //隐藏下划线
                    //border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.grey),
                    contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                  ),
                  onChanged: (text) {
                    code = text;
                  },
                ),
              ),
            ),
          ),
          Visibility(
            visible: layoutOrder,
            child: Row(
              children: [
                Text(
                  "Order: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: ElevatedButton(
                    child: Row(
                      children: [
                        Expanded(
                            child: Text(
                          Utils.getStringisEmpty(order),
                          style: TextStyle(
                            color: MyAppTheme.darkText,
                          ),
                        )),
                        Icon(
                          Icons.keyboard_arrow_down,
                          size: 20,
                          color: MyAppTheme.nearlyBlue,
                        ),
                      ],
                    ),
                    style: ButtonStyle(
                      textStyle: MaterialStateProperty.all(
                        Theme.of(context).textTheme.subtitle1,
                      ),
                      alignment: Alignment.centerLeft,
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          side: BorderSide(width: 1, color: MyAppTheme.nearlyBlue),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                      ),
                    ),
                    onPressed: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      print("object");
                      if (b2BTrailers == null || b2BTrailers.length == 0) {
                        return;
                      }
                      print("2222222");
                      JhPickerTool.showStringPicker(context, data: b2BTrailers, clickCallBack: (int index, var str) {
                        print(index);
                        print(str);
                        b2BTrailer = b2BTrailers[index];
                        order = b2BTrailer.jobId;

                        layoutPalletTag = true;
                        if (b2BTrailer.isPalletTag == null) {
                          b2BTrailer.isPalletTag = false;
                        }
                        if (b2BTrailer.isPalletTag) {
                          //是否托盘标 true是 false否
                          tvPalletHint = true;
                          tvPrint = true;
                          tvPallet = "Pallet tag required.";
                        } else {
                          tvPallet = "No pallet tag found.";
                          tvPrint = false;
                          tvPalletHint = false;
                        }
                      });
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(flex: 1, child: Text("")),
          Visibility(
              visible: layoutPalletTag,
              child: Row(
                children: [
                  Expanded(
                      child: Text(
                    Utils.getStringisEmpty(tvPallet),
                    style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
                  )),
                  Visibility(
                      visible: tvPrint,
                      child: GestureDetector(
                        child: SizedBox(
                          height: 35, // 高度
                          child: ElevatedButton(
                            child: Text(
                              "Print",
                              style: TextStyle(color: MyAppTheme.white, fontSize: 14.0),
                            ),
                            style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                              shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                RoundedRectangleBorder(
                                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                                ),
                              ),
                            ),
                            onPressed: () {},
                          ),
                        ),
                      )),
                ],
              )),
          SizedBox(
            height: 5,
          ),
          Visibility(
            visible: tvPalletHint,
            child: Text(
              "please download it from WMS or E-mail and print it manually.",
              style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
            ),
          ),
          SizedBox(
            height: 5,
          )
        ],
      ),
    );
  }

  void getTrailerInitData() async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["type"] = "B2B";
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getTrailerInitData, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      trailerBean = TrailerBean.fromJson(baseResponse.data);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
    b2bPendingTrailer();
  }

  void b2bPendingTrailer() async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["type"] = 7;
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.b2bPendingTrailer, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      b2BTrailers = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => B2BTrailer.fromJson(userJson)).toList());
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void appTrailer(String trailer) async {
    updateHint('');
    TrailerTypeQr trailerTypeQr = new TrailerTypeQr();
    trailerTypeQr.trailer = trailer;
    trailerTypeQr.type = 8;
    String json = jsonEncode(trailerTypeQr);
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.appTrailer, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      TrailerType trailerType = TrailerType.fromJson(baseResponse.data);

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => B2BTrailerLogisticsScreen(trailerType: trailerType)),
      ).then((value) => {
            if ((value != null) && value)
              {
                setState(() {
                  textEditingController.text = "";
                })
              }
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    switch (type) {
      case 1:
        if (Utils.isEmpty(textEditingController.text)) {
          ToastContext().init(context);
          Toast.show("scan trailer#", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        appTrailer(textEditingController.text);
        break;
      case 2:
        if ((b2BTrailers != null) && (b2BTrailers.length > 0)) {
          if (Utils.isEmpty(order)) {
            Toast.show("Please select the order", duration: Toast.lengthShort, gravity: Toast.bottom);
            return;
          }
        }
        B2bTrailerQr trailerTypeQr = new B2bTrailerQr();
        if (!Utils.isEmpty(order)) {
          trailerTypeQr.jobId = b2BTrailer.jobId;
          trailerTypeQr.refId = b2BTrailer.refId;
        }
        trailerTypeQr.type = 7;
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => B2BTrailerSelfpickupScreen(b2bTrailerQr: trailerTypeQr)),
        ).then((value) => {
              if ((value != null) && value)
                {
                  _updateRadio(type),
                  b2bPendingTrailer()
                }
            });
        break;
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class TrailerTypeQr {
  String trailer; //车牌号
  int type = 1;

  Map<String, dynamic> toJson() {
    return {
      "trailer": this.trailer,
      "type": this.type,
    };
  } //类型 1:B2C Packing  2:B2B Packing  3:B2B FTL  4:B2B LTL 5:Transfer 6:return

}
